#!/usr/bin/env node
/**
 * Phase4 面板注册完整性验证脚本
 * 生成 phase4/panel-validation.json
 */

const fs = require('fs');
const path = require('path');

function validatePanelRegistration(componentName) {
  console.log(`🔍 验证 ${componentName} 的面板注册完整性...`);

  const results = {
    success: true,
    issues: [],
    warnings: [],
    customPanels: {
      list: [],
      block: ''
    }
  };

  try {
    const editFieldsPath = 'src/components/editor/schema/edit/aiComponents.ts';
    const editFieldsContent = fs.readFileSync(editFieldsPath, 'utf8');

    const customPanels = extractCustomPanels(editFieldsContent, componentName);
    results.customPanels = customPanels;
    console.log(`📋 发现自定义面板: ${customPanels.list.join(', ') || '无'}`);

    const rightIndexPath = 'src/components/editor/Right/index.tsx';
    const rightIndexContent = fs.readFileSync(rightIndexPath, 'utf8');

    const filterValidation = validateFilterArrays(rightIndexContent, customPanels.list);
    results.issues.push(...filterValidation.issues);
    results.warnings.push(...filterValidation.warnings);

    const renderValidation = validateRenderConditions(rightIndexContent, customPanels.list);
    results.issues.push(...renderValidation.issues);

    const expandValidation = validateDefaultExpand(rightIndexContent, customPanels.list);
    results.issues.push(...expandValidation.issues);

    const mapValidation = validateHeaderMapping(rightIndexContent, customPanels.list);
    results.issues.push(...mapValidation.issues);

    if (results.issues.length > 0) {
      results.success = false;
    }

  } catch (error) {
    results.success = false;
    results.issues.push(`验证过程出错: ${error.message}`);
  }

  return results;
}

function extractCustomPanels(editFieldsContent, componentName) {
  const result = { list: [], block: '' };
  const regex = new RegExp(`${componentName}:\\s*\\[([\\s\\S]*?)\\]`, 'g');
  const match = regex.exec(editFieldsContent);

  if (match) {
    const fieldsArray = match[1];
    result.block = fieldsArray;
    const belongToMatches = fieldsArray.match(/belongTo:\s*['"`]([^'"`]+)['"`]/g);

    if (belongToMatches) {
      belongToMatches.forEach(match => {
        const belongTo = match.match(/belongTo:\s*['"`]([^'"`]+)['"`]/)[1];
        if (belongTo.startsWith('render') && !result.list.includes(belongTo)) {
          result.list.push(belongTo);
        }
      });
    }
  }

  return result;
}

function validateFilterArrays(content, customPanels) {
  const issues = [];
  const warnings = [];

  const basicArrayMatch = content.match(/basicUploadPublishArr.*?\[([\s\S]*?)\]/);
  if (basicArrayMatch) {
    const contentPanels = customPanels.filter(panel =>
      !panel.includes('Style') && !panel.includes('Chart')
    );

    contentPanels.forEach(panel => {
      if (!basicArrayMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Content面板 '${panel}' 未添加到 basicUploadPublishArr`);
      }
    });
  }

  const styleArrayMatch = content.match(/stylePublishArr.*?\[([\s\S]*?)\]/);
  if (styleArrayMatch) {
    const stylePanels = customPanels.filter(panel =>
      panel.includes('Style') || panel.includes('Chart')
    );

    stylePanels.forEach(panel => {
      if (!styleArrayMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Style面板 '${panel}' 未添加到 stylePublishArr`);
      }
    });
  }

  return { issues, warnings };
}

function validateRenderConditions(content, customPanels) {
  const issues = [];
  const getRenderContentMatch = content.match(/getRenderContent.*?\[([\s\S]*?)\]/);
  if (getRenderContentMatch) {
    const contentPanels = customPanels.filter(panel =>
      !panel.includes('Style') && !panel.includes('Chart')
    );

    contentPanels.forEach(panel => {
      if (!getRenderContentMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Content面板 '${panel}' 未添加到 getRenderContent 条件检查`);
      }
    });
  }
  return { issues };
}

function validateDefaultExpand(content, customPanels) {
  const issues = [];
  const defaultActiveKeyMatches = content.match(/defaultActiveKey:\s*\[([\s\S]*?)\]/g) || [];

  customPanels.forEach(panel => {
    let found = false;
    defaultActiveKeyMatches.forEach(match => {
      if (match.includes(`'${panel}'`)) {
        found = true;
      }
    });

    if (!found) {
      issues.push(`⚠️ 面板 '${panel}' 未添加到 defaultActiveKey（可选，影响默认展开）`);
    }
  });

  return { issues };
}

function validateHeaderMapping(content, customPanels) {
  const issues = [];

  customPanels.forEach(panel => {
    const headerMapPattern = new RegExp(`${panel}:\\s*\\{[\\s\\S]*?render:`, 'g');
    if (!headerMapPattern.test(content)) {
      issues.push(`❌ 面板 '${panel}' 未在 headerMap 中配置映射关系`);
    }
  });

  return { issues };
}

function computeFieldCoverage(componentName, editFieldsBlock) {
  const specPath = path.join(process.cwd(), componentName, 'phase3/custom-panel-spec.json');
  if (!fs.existsSync(specPath)) {
    return { total: 0, covered: 0, missing: [], rate: 1 };
  }

  const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
  const fields = (spec.panels || []).flatMap(panel => panel.fields || []);
  if (fields.length === 0) {
    return { total: 0, covered: 0, missing: [], rate: 1 };
  }

  const coveredFields = [];
  const missingFields = [];

  fields.forEach(field => {
    const regex = new RegExp(`key:\\s*['"\`]${field}['"\`]`);
    if (regex.test(editFieldsBlock || '')) {
      coveredFields.push(field);
    } else {
      missingFields.push(field);
    }
  });

  return {
    total: fields.length,
    covered: coveredFields.length,
    missing: missingFields,
    rate: coveredFields.length / fields.length
  };
}

function buildReport(componentName, validationResult, coverage) {
  const panelDetails = validationResult.customPanels.list.map(panel => {
    const panelIssues = validationResult.issues.filter(msg => msg.includes(`'${panel}'`));
    const panelWarnings = validationResult.warnings.filter(msg => msg.includes(`'${panel}'`));
    return {
      belongTo: panel,
      status: panelIssues.length === 0 ? 'pass' : 'fail',
      issues: panelIssues,
      warnings: panelWarnings
    };
  });

  return {
    component: componentName,
    timestamp: new Date().toISOString(),
    success: validationResult.success,
    panels: panelDetails,
    issues: validationResult.issues,
    warnings: validationResult.warnings,
    fieldCoverage: coverage
  };
}

function writeReport(report, outputPath) {
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
  fs.writeFileSync(outputPath, JSON.stringify(report, null, 2));
  console.log(`📄 输出报告: ${outputPath}`);
}

function parseArgs() {
  const args = process.argv.slice(2);
  const componentName = args[0];
  if (!componentName) {
    console.error('用法: node scripts/phase4-panel-validation.js <ComponentName> [--output path]');
    process.exit(1);
  }

  let output;
  const outputFlagIndex = args.indexOf('--output');
  if (outputFlagIndex !== -1 && args[outputFlagIndex + 1]) {
    output = path.resolve(args[outputFlagIndex + 1]);
  } else {
    output = path.join(process.cwd(), componentName, 'phase4/panel-validation.json');
  }

  return { componentName, output };
}

function main() {
  const { componentName, output } = parseArgs();
  const validationResult = validatePanelRegistration(componentName);
  const coverage = computeFieldCoverage(componentName, validationResult.customPanels.block);
  const report = buildReport(componentName, validationResult, coverage);
  writeReport(report, output);

  console.log('\n📊 验证结果:');
  if (validationResult.success) {
    console.log('✅ 面板注册完整');
  } else {
    console.log('❌ 发现面板注册问题，详见报告');
  }

  process.exit(validationResult.success ? 0 : 1);
}

if (require.main === module) {
  main();
}

module.exports = { validatePanelRegistration };
